<template>
	<view class="address_edit">
		<!-- 导航栏 -->
		<view class="uni-nav-bar">
			<view class="nav-left" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<view class="nav-title">{{ pageTitle }}</view>
			<view class="nav-right"></view>
		</view>

		<!-- 编辑表单 -->
		<view class="address-form">
			<!-- 收件人 -->
			<view class="form-item">
				<text class="form-label">收件人</text>
				<input 
					v-model="addressInfo.name" 
					class="form-input" 
					placeholder="请输入收件人姓名"
					maxlength="20"
				>
			</view>

			<!-- 手机号 -->
			<view class="form-item">
				<text class="form-label">手机号</text>
				<input 
					v-model="addressInfo.tel" 
					class="form-input" 
					type="number" 
					placeholder="请输入手机号"
					maxlength="11"
				>
			</view>

			<!-- 地区选择 -->
			<view class="form-item">
				<text class="form-label">地区</text>
				<picker 
					@change="onAreaPickerChange" 
					@columnchange="onAreaColumnChange" 
					mode="multiSelector"
					:range="areaRange" 
					:value="areaPickerValue"
					:disabled="isLoading"
				>
					<view class="area-picker">
						<text v-if="addressInfo.province && addressInfo.city && addressInfo.county">
							{{ addressInfo.province }} {{ addressInfo.city }} {{ addressInfo.county }}
						</text>
						<text v-else class="placeholder">请选择省/市/区</text>
					</view>
				</picker>
			</view>

			<!-- 详细地址 -->
			<view class="form-item">
				<text class="form-label">详细地址</text>
				<input 
					v-model="addressInfo.addressDetail" 
					class="form-input" 
					placeholder="请输入街道、门牌号等详细信息"
					maxlength="100"
				>
			</view>

			<!-- 默认地址 -->
			<view class="form-item checkbox-item">
				<checkbox 
					v-model="addressInfo.isDefault" 
					class="form-checkbox"
					:disabled="isLoading"
				></checkbox>
				<text>设为默认地址</text>
			</view>

			<!-- 操作按钮 -->
			<view class="button-group">
				<button 
					class="delete-btn" 
					v-if="id !== 'new'" 
					@click="onDelete"
					:disabled="isLoading"
				>
					删除地址
				</button>
				<button 
					class="save-btn" 
					@click="onSave"
					:disabled="isLoading"
				>保存地址</button>
			</view>
		</view>

		<!-- 加载中 -->
		<view class="loading-mask" v-if="isLoading">
			<view class="loading-content">
				<view class="spinner"></view>
				<text>处理中...</text>
			</view>
		</view>
	</view>
</template>

<script>
import areaData from '@/api/areaFromVant.js';

export default {
	props: ["id"],
	data() {
		return {
			addressInfo: {
				id: '',
				name: '',
				tel: '',
				province: '',
				city: '',
				county: '',
				addressDetail: '',
				isDefault: false
			},
			areaRange: [[], [], []], // 省/市/区列表
			areaPickerValue: [0, 0, 0],
			isLoading: false,
			// 关键优化：存储完整的编码映射（包含名称），避免匹配偏差
			areaMap: {
				provinces: [], // 格式：[{ code: 'xxx', name: 'xxx' }]
				cities: {},    // 格式：{ 省份code: [{ code: 'xxx', name: 'xxx' }] }
				counties: {}   // 格式：{ 城市code: [{ code: 'xxx', name: 'xxx' }] }
			}
		};
	},
	computed: {
		pageTitle() {
			return this.id === "new" ? "新增地址" : "编辑地址";
		}
	},
	created() {
		this.initAreaData();
		if (this.id === "new") {
			this.resetForm();
		} else {
			this.getAddressDetail();
		}
	},
	methods: {
		// 初始化地区数据（核心修复：完整存储编码和名称映射）
		initAreaData() {
			const { province_list, city_list, county_list } = areaData;

			// 1. 处理省份数据
			this.areaMap.provinces = Object.keys(province_list)
				.sort()
				.map(code => ({ code, name: province_list[code] }));
			this.areaRange[0] = this.areaMap.provinces.map(item => item.name);

			// 2. 处理城市数据（按省份编码前缀分组，存储完整信息）
			this.areaMap.provinces.forEach(province => {
				const provincePrefix = province.code.substring(0, 2);
				this.areaMap.cities[province.code] = Object.keys(city_list)
					.filter(cityCode => cityCode.startsWith(provincePrefix))
					.sort()
					.map(code => ({ code, name: city_list[code] }));
			});

			// 3. 处理区县数据（按城市编码前缀分组，存储完整信息）
			Object.keys(city_list).forEach(cityCode => {
				const cityPrefix = cityCode.substring(0, 4);
				this.areaMap.counties[cityCode] = Object.keys(county_list)
					.filter(countyCode => countyCode.startsWith(cityPrefix))
					.sort()
					.map(code => ({ code, name: county_list[code] }));
			});

			// 初始化默认省市区（确保有数据才更新）
			if (this.areaMap.provinces.length > 0) {
				const firstProvince = this.areaMap.provinces[0];
				this.updateCityRange(firstProvince.code);
				
				const firstCities = this.areaMap.cities[firstProvince.code] || [];
				if (firstCities.length > 0) {
					this.updateCountyRange(firstCities[0].code);
				}
			}
		},

		// 更新城市列表（核心修复：按省份code精准匹配）
		updateCityRange(provinceCode) {
			const cities = this.areaMap.cities[provinceCode] || [];
			this.areaRange[1] = cities.map(item => item.name);
			this.areaPickerValue[1] = 0; // 重置城市索引

			// 同步更新区县列表（基于新选中的第一个城市）
			if (cities.length > 0) {
				this.updateCountyRange(cities[0].code);
			} else {
				this.areaRange[2] = [];
				this.areaPickerValue[2] = 0;
			}
		},

		// 更新区县列表（核心修复：按城市code精准匹配）
		updateCountyRange(cityCode) {
			const counties = this.areaMap.counties[cityCode] || [];
			this.areaRange[2] = counties.map(item => item.name);
			this.areaPickerValue[2] = 0; // 重置区县索引
		},

		// 地区列切换事件（核心修复：基于code联动，避免索引偏差）
		onAreaColumnChange(e) {
			const { column, value } = e.detail;
			this.areaPickerValue[column] = value; // 同步选中索引

			// 省份列切换
			if (column === 0) {
				const selectedProvince = this.areaMap.provinces[value];
				this.updateCityRange(selectedProvince.code);
			}
			// 城市列切换
			else if (column === 1) {
				const selectedProvince = this.areaMap.provinces[this.areaPickerValue[0]];
				const selectedCity = this.areaMap.cities[selectedProvince.code][value];
				this.updateCountyRange(selectedCity.code);
			}
		},

		// 地区选择确认事件（核心修复：通过code映射名称，确保匹配准确）
		onAreaPickerChange(e) {
			const [pIdx, cIdx, aIdx] = e.detail.value;

			// 精准匹配选中的省市区
			const selectedProvince = this.areaMap.provinces[pIdx];
			const selectedCity = this.areaMap.cities[selectedProvince.code][cIdx];
			const selectedCounty = this.areaMap.counties[selectedCity.code][aIdx];

			// 更新地址信息
			this.addressInfo.province = selectedProvince.name;
			this.addressInfo.city = selectedCity.name;
			this.addressInfo.county = selectedCounty.name;
		},

		// 获取地址详情
		getAddressDetail() {
			try {
				const addressList = uni.getStorageSync('addressList') || [];
				const target = addressList.find(item => item.id === this.id);
				
				if (target) {
					this.addressInfo = { ...target };
					this.$nextTick(() => {
						this.matchAreaPickerIndex(); // DOM更新后再匹配索引
					});
				} else {
					uni.showToast({ title: '地址不存在', icon: 'none', duration: 1500 });
					setTimeout(() => this.goBack(), 1500);
				}
			} catch (error) {
				uni.showToast({ title: '获取地址失败', icon: 'none', duration: 1500 });
				setTimeout(() => this.goBack(), 1500);
			}
		},

		// 匹配地区选择器索引（核心修复：通过名称反向查找code，确保关联正确）
		matchAreaPickerIndex() {
			const { province, city, county } = this.addressInfo;
			if (!province || !city || !county) return;

			// 1. 查找省份索引
			const pIdx = this.areaMap.provinces.findIndex(item => item.name === province);
			if (pIdx === -1) return;

			// 2. 查找城市索引（基于省份code过滤）
			const selectedProvince = this.areaMap.provinces[pIdx];
			const cities = this.areaMap.cities[selectedProvince.code] || [];
			const cIdx = cities.findIndex(item => item.name === city);
			if (cIdx === -1) return;

			// 3. 查找区县索引（基于城市code过滤）
			const selectedCity = cities[cIdx];
			const counties = this.areaMap.counties[selectedCity.code] || [];
			const aIdx = counties.findIndex(item => item.name === county);

			// 同步索引和地区列表
			this.areaPickerValue = [pIdx, cIdx, aIdx > -1 ? aIdx : 0];
			this.updateCityRange(selectedProvince.code);
			this.updateCountyRange(selectedCity.code);
		},

		// 重置表单
		resetForm() {
			this.addressInfo = {
				id: '',
				name: '',
				tel: '',
				province: '',
				city: '',
				county: '',
				addressDetail: '',
				isDefault: false
			};
			this.areaPickerValue = [0, 0, 0];

			// 重置地区选择器显示
			if (this.areaMap.provinces.length > 0) {
				const firstProvince = this.areaMap.provinces[0];
				const firstCities = this.areaMap.cities[firstProvince.code] || [];
				const firstCounties = firstCities.length > 0 
					? this.areaMap.counties[firstCities[0].code] || [] 
					: [];

				this.addressInfo.province = firstProvince.name;
				this.addressInfo.city = firstCities.length > 0 ? firstCities[0].name : '';
				this.addressInfo.county = firstCounties.length > 0 ? firstCounties[0].name : '';
			}
		},

		// 保存地址
		onSave() {
			// 表单验证
			if (!this.addressInfo.name) return uni.showToast({ title: '请输入收件人', icon: 'none' });
			if (!this.addressInfo.tel || this.addressInfo.tel.length !== 11) {
				return uni.showToast({ title: '请输入正确手机号', icon: 'none' });
			}
			if (!this.addressInfo.province || !this.addressInfo.city || !this.addressInfo.county) {
				return uni.showToast({ title: '请选择完整地区', icon: 'none' });
			}
			if (!this.addressInfo.addressDetail) return uni.showToast({ title: '请输入详细地址', icon: 'none' });

			this.isLoading = true;
			let addressList = uni.getStorageSync('addressList') || [];

			// 新增地址
			if (this.id === "new") {
				this.addressInfo.id = Date.now().toString(); // 生成唯一ID
				addressList.push(this.addressInfo);
			}
			// 编辑地址
			else {
				const index = addressList.findIndex(item => item.id === this.id);
				if (index !== -1) addressList[index] = this.addressInfo;
			}

			// 处理默认地址（保证唯一）
			if (this.addressInfo.isDefault) {
				addressList = addressList.map(item => ({
					...item,
					isDefault: item.id === this.addressInfo.id
				}));
				uni.setStorageSync('chosenAddressId', this.addressInfo.id);
			}

			// 保存到本地存储
			uni.setStorageSync('addressList', addressList);

			// 保存成功后返回列表页
			setTimeout(() => {
				this.isLoading = false;
				uni.showToast({ title: '保存成功' });
				uni.navigateBack({ delta: 1 });
			}, 500);
		},

		// 删除地址
		onDelete() {
			uni.showModal({
				title: '提示',
				content: '确定删除该地址吗？',
				success: (res) => {
					if (res.confirm) {
						this.isLoading = true;
						let addressList = uni.getStorageSync('addressList') || [];
						addressList = addressList.filter(item => item.id !== this.id);

						// 如果删除的是默认地址，清空选中状态
						if (this.addressInfo.isDefault) {
							uni.setStorageSync('chosenAddressId', '');
						}
						uni.setStorageSync('addressList', addressList);

						setTimeout(() => {
							this.isLoading = false;
							uni.showToast({ title: '删除成功' });
							uni.navigateBack({ delta: 1 });
						}, 500);
					}
				}
			});
		},

		// 返回上一页
		goBack() {
			uni.navigateBack({ delta: 1 });
		}
	}
};
</script>
<style scoped lang="less">
	.address_edit {
		background-color: #f0f0f0;
		min-height: 100vh;
		font-size: 14px;
	}

	.uni-nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 44px;
		background-color: #fff;
		padding: 0 15px;
		border-bottom: 1px solid #eee;

		.nav-left {
			width: 44px;
			height: 44px;
			display: flex;
			align-items: center;
			justify-content: center;

			.back-icon {
				font-size: 20px;
				color: #333;
			}
		}

		.nav-title {
			flex: 1;
			text-align: center;
			font-size: 16px;
			font-weight: bold;
			color: #333;
		}

		.nav-right {
			width: 44px;
			height: 44px;
		}
	}

	.address-form {
		background-color: #fff;
		margin: 10px;
		border-radius: 8px;
		padding: 15px;

		.form-item {
			display: flex;
			align-items: center;
			padding: 12px 0;
			border-bottom: 1px solid #eee;

			&:last-child {
				border-bottom: none;
			}
		}

		.form-label {
			width: 80px;
			color: #333;
		}

		.form-input {
			flex: 1;
			height: 30px;
			line-height: 30px;
			color: #333;
		}

		.area-picker {
			flex: 1;
			min-height: 30px;
			line-height: 30px;
			color: #333;

			.placeholder {
				color: #ccc;
			}
		}

		.checkbox-item {
			padding-left: 80px;

			.form-checkbox {
				margin-right: 10px;
			}
		}

		.button-group {
			display: flex;
			justify-content: space-between;
			margin-top: 20px;

			.delete-btn {
				width: 48%;
				background-color: #fff;
				color: #e74c3c;
				border: 1px solid #e74c3c;
				border-radius: 5px;
				padding: 10px 0;
			}

			.save-btn {
				width: 48%;
				background-color: #e74c3c;
				color: #fff;
				border: none;
				border-radius: 5px;
				padding: 10px 0;
			}
		}
	}

	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.3);
		z-index: 1000;
		display: flex;
		align-items: center;
		justify-content: center;

		.loading-content {
			background-color: #fff;
			padding: 20px;
			border-radius: 8px;
			display: flex;
			flex-direction: column;
			align-items: center;

			.spinner {
				width: 30px;
				height: 30px;
				border: 3px solid #eee;
				border-top-color: #e74c3c;
				border-radius: 50%;
				animation: spin 1s linear infinite;
				margin-bottom: 10px;
			}
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}
</style>